package com.weijun.keepalive.utils

import android.content.Context
import android.media.MediaPlayer

/**
 * @author: weijun
 * date: 2023/7/6
 * description:
 */
internal object MediaPlayerUtil {

    private lateinit var player: MediaPlayer

    val isPlaying:Boolean
        get() {
            if (::player.isInitialized) {
                return player.isPlaying
            }
            return false
        }

    fun init(context: Context,rawId:Int,completion:() -> Unit){
        player = MediaPlayer.create(context, rawId).apply {
            setVolume(0f, 0f)
            setOnErrorListener { _, _, _ -> false }
            setOnCompletionListener { completion.invoke() }
            play()
        }
    }

    fun play(){
        if (::player.isInitialized && !player.isPlaying) {
            player.start()
        }
    }

    fun pause(){
        if (::player.isInitialized && player.isPlaying) {
            player.pause()
        }
    }
}